package com.client.utils;

import com.client.entity.B_client;
import com.client.entity.Message;
import com.client.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

import static java.lang.Thread.sleep;

@Slf4j
@EnableAsync
@Component
public class MessageHandler {
    @Autowired
    MessageService messageService;
    @Autowired
    UDPUtil udp;

    //开启一个线程，用来处理消息重发
    @Async
    public void messageResendHandler() {
        List<Message> messages = messageService.getMessages();
        log.info("开启消息重发服务");
        while (true) {
            if (!messages.isEmpty()) {
                for (Message message : messages) {
                    if ((MessageUtils.getNowTime().getTime() - message.getTime().getTime()) > message.getTimeout() * 1000L) {
                        MessageService.deleteMessage(message.getUid());
                        log.info("消息超时");
//                        message.sendFalsed();

                    } else if ((MessageUtils.getNowTime().getTime() - message.getTime().getTime()) / (message.getInterval_time() * 1000L) >
                            message.getCount()) {
                        udp.send(message.getIp(), message.getPort(), message.getMsg());
                        message.addCount();
                        log.info(messageService.getClient(message.getUid())+"第" + message.getCount() + "次重发包");
                    }
                    if (messages.isEmpty())
                        break;
                }
            }
            try {
                sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    //开启一个线程，用来处理认证超时
    @Async
    public void CertificationMessageResendHandler() {
        Map<String, B_client> clients = messageService.getClients();
        log.info("删除认证超时");
        while (true) {
            if (!clients.isEmpty()) {
                for (Map.Entry<String, B_client> client : clients.entrySet()) {
//                    log.info("[" + client.getKey() + "]的认证已经过" +
//                            (MessageUtils.getNowTime().getTime()-  client.getValue().getTime().getTime()) / 1000 + "s没收到回复");
                    if (MessageUtils.getNowTime().getTime() - client.getValue().getTime().getTime() > 30 * 1000) {
                        if (client.getValue().getExchang_flag() != -2)
                            log.info("[" + client.getKey() + "]的认证因消息超时而失败");
                        messageService.deleteClient(client.getKey());
                    }
                }
            }
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
